const gulp = require('gulp')
const cssmin = require('gulp-cssmin')
const autoprefixer = require('gulp-autoprefixer')
const sass = require('gulp-sass')(require('sass'))
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const htmlmin = require('gulp-htmlmin')
const del = require('del')

// 打包 css
const cssHandler = () => {
  // 让 gulp 跟你岁 任务流
  // 把任务流 return 出去
  return gulp
    .src('./src/css/*.css')
    .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(gulp.dest('./dist/css/'))
}
// 打包 sass
const sassHandler = () => {
  return gulp
    .src('./src/sass/*.scss')
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(gulp.dest('./dist/sass/'))
}
// 打包 js
const jsHandler = () => {
  return gulp
    .src('./src/js/*.js')
    .pipe(babel({presets: ['@babel/preset-env']}))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js/'))
}
// 打包 html
const htmlHandler = () => {
  return gulp
    .src('./src/view/*.html')
    .pipe(htmlmin({
      // 配置项
      // 去掉多余空白
      collapseWhitespace: true,
      // 简写布尔类型属性
      collapseBooleanAttributes: true,
      // 去除双引号
      removeAttributeQuotes: true,
      // 移除空属性
      removeEmptyAttributes: true,
      // 移除注释
      removeComments: true,
      // 移除 link 标签和 style 标签身上的默认 type 属性
      removeScriptTypeAttributes: true,
      // 压缩内嵌式 css 样式
      minifyCSS: true,
      // 压缩内嵌式 js 代码
      minifyJS: true
    }))
    .pipe(gulp.dest('./dist/view/'))
}
// 压缩图片
const imgHandler = () => {
  return gulp
    .src('./src/images/*.**')
    // .pipe(imagemin())
    .pipe(gulp.dest('./dist/images/'))
}
// 转存 视频
const videoHandler = () => {
  return gulp
    .src('./src/vedios/*.**')
    .pipe(gulp.dest('./dist/videos/'))
}
const audioHandler = () => {
  return gulp
    .src('./src/audios/*.**')
    .pipe(gulp.dest('./dist/audios/'))
}
// 转存 fonts 文件
const fontHandler = () => {
  return gulp
    .src('./fonts/*.**')
    .pipe(gulp.dest('./dist/fonts/'))
}
// 删除任务
const delHandler = () => {
  return del(['./dist/'])
}
// 配置监控任务
const watchHandler = () => {
  gulp.watch('./src/view/*.html', htmlHandler)
  gulp.watch('./src/css/*.css', cssHandler)
  gulp.watch('./src/js/*.js', jsHandler)
  gulp.watch('./src/sass/*.scss', sassHandler)
}
const _default = gulp.series(
  delHandler,
  gulp.parallel(cssHandler, sassHandler, htmlHandler, jsHandler, imgHandler, videoHandler, audioHandler, fontHandler),
  watchHandler
)
// 导出创建的任务
module.exports = {
  htmlHandler,
  default: _default
}